#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <gmp.h>
#include <time.h>

int main(void) {
	int i = 0;
    clock_t start,end;

	mpf_t aBef, aAft, b, t, p, pi, aux1;
    mpf_init2(aBef,40000000);
	mpf_init2(aAft,40000000);
	mpf_init2(b,40000000);
	mpf_init2(t,40000000);
	mpf_init2(p,40000000);
	mpf_init2(pi,40000000);
	mpf_init(aux1);

    mpf_set_d(pi,0.0);
    mpf_set_d(p,1);
    mpf_set_d(aAft,0);
  	mpf_set_d(aBef,1);
	mpf_set_d(aux1,4);

	mpf_sqrt_ui(b,2);
	mpf_ui_div(b,1,b);  //iniciando b

    start=clock();
	mpf_ui_div(t,1,aux1);    //iniciando t

     	for(i = 0;i < 24;i++) {
		   mpf_add(aAft,aBef,b);
		   mpf_div_ui(aAft,aAft,2);   // aAft = (aBef + b)/2;

		   mpf_mul(b,aBef,b);
		   mpf_sqrt(b,b);        // b =  sqrt(aBef*b);

		   mpf_sub(aBef,aBef,aAft);
		   mpf_pow_ui(aBef,aBef,2);
		   mpf_mul(aBef,p,aBef);
		   mpf_sub(t,t,aBef);  	   //t = t - p*pow((aBef - aAft),2);

		   mpf_mul_ui(p,p,2);    //p = 2*p;

		   mpf_set(aBef,aAft);	  //aBef = aAft;
    	}

	mpf_add(aBef,aBef,b);
	mpf_pow_ui(aBef,aBef,2);
	mpf_mul_ui(t,t,4 );
	mpf_div(pi,aBef,t);  	 //pi = (pow((aBef + b),2))/(4*t);

    end=clock();
   	gmp_printf("Pi = %.10000000Ff\n",pi);
   	printf("\n--Tempo %ld--\n",(end - start)/CLOCKS_PER_SEC);

	mpf_clear(aux1);
	mpf_clear(aBef);
	mpf_clear(aAft);
	mpf_clear(b);
	mpf_clear(t);
	mpf_clear(p);
	mpf_clear(pi);

	return 0;
}
